package com.fjjn.component;

import com.fjjn.enums.RedisDelayQueueEnum;
import com.fjjn.service.RedisDelayQueueCallbackService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
@ConditionalOnBean({RedissionDelayQueueService.class})
public class RedisDelayQueueRunner implements CommandLineRunner {

    private final RedissionDelayQueueService redissionDelayQueueService;

    public RedisDelayQueueRunner(RedissionDelayQueueService redissionDelayQueueService) {
        this.redissionDelayQueueService = redissionDelayQueueService;
    }

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private ThreadPoolExecutor delayQueueThreadPoolExecutor;

    @Override
    public void run(String... args) throws Exception {
        log.info(">>>准备延迟队列监听");
        new Thread(() -> {
            while (true) {
                for (RedisDelayQueueEnum delayQueueEnum : RedisDelayQueueEnum.values()) {
                    try {
                        Object delayQueue = redissionDelayQueueService.getDelayQueue(delayQueueEnum.getCode());
                        if (delayQueue != null) {
                            RedisDelayQueueCallbackService<Object> callbackService = (RedisDelayQueueCallbackService) applicationContext.getBean(delayQueueEnum.getBeanId());
                            delayQueueThreadPoolExecutor.execute(()->{
                                callbackService.callback(delayQueue);
                            });
                        }
                    } catch (InterruptedException e) {
                        log.error("(Redission延迟队列监测异常中断) {}", e.getMessage());
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
        log.info("延迟队列监听中");

    }
}
